package com.hoopchina.util;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;

/**
 * Class for retrieving string/image resources for class 
 *   which is not inherited from View class
 * @author Si Wei
 * @since 1.0
 */
public class ResourceUtils {
	private static Context        mMainContext;                   // resource handler
	
	/**
	 * Set the resource handler
	 * @param aContext
	 */
	public static void setContext( Context aContext ) {
		mMainContext = aContext;
	}
	
	/**
	 * Get string
	 * @param aResource resource id
	 * @return string
	 */
	public static String getString( int aResource ) {
		return mMainContext.getString( aResource );
	}
	
	/**
	 * Get drawable object
	 * @param aResource resource id
	 * @return drawable
	 */
	public static Drawable getDrawable( int aResource ) {
		return mMainContext.getResources().getDrawable( aResource );
	}
	
	public static String getStringFromFile( String aFile ) {
		String ret = null;
		try {  
			InputStream inputStream = mMainContext.getAssets().open( aFile );
			int size = inputStream.available();
			byte[] buffer = new byte[size];
			inputStream.read( buffer );
			inputStream.close();
			ret = new String( buffer, "UTF-8" );
			} 
		catch ( IOException e ) {
			e.printStackTrace();
		}
		return ret;
	}
	
    public static Bitmap getRoundedCornerBitmap( 
    		Bitmap aBitmap, int aWidth, int aHeight,
    		int aRadius, int aColor ) {
    	Bitmap resizeBitmap = Bitmap.createScaledBitmap( aBitmap, aWidth, aHeight, true );
        Bitmap ret = Bitmap.createBitmap( aWidth, aHeight, Config.ARGB_8888 );
        Canvas canvas = new Canvas( ret );

        final Paint paint = new Paint();
        final Rect rect = new Rect( 0, 0, aWidth, aHeight );
        final RectF rectF = new RectF( rect );

        paint.setAntiAlias( true );
        canvas.drawARGB( 0, 0, 0, 0 );
        paint.setColor( aColor );
        canvas.drawRoundRect( rectF, aRadius, aRadius, paint );

        paint.setXfermode( new PorterDuffXfermode( Mode.SRC_IN ) );
        canvas.drawBitmap( resizeBitmap, rect, rect, paint );

        return ret;
    }
}
